package nettyTest.netty3Test.httpcors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import qps.QPSCalculator;

public class OkResponseHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        super.channelActive(ctx);
        System.out.println("OkResponseHandler ========== channelActive");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        System.out.println("OkResponseHandler ========== channelRegistered");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (!(msg instanceof FullHttpRequest)) {
            DefaultHttpRequest request = (DefaultHttpRequest) msg;
            System.out.println(request.uri());
        }
        FullHttpRequest request = (FullHttpRequest) msg;
        System.out.println(request.method().toString());
        System.out.println(request.uri());
        System.out.println(request.headers().get(HttpHeaderNames.CONTENT_TYPE));
        ByteBuf contentByteBuf = request.content();
        int i = contentByteBuf.readableBytes();
        byte[] bytes = new byte[i];
        contentByteBuf.readBytes(bytes);
        String contentStr = new String(bytes);
        contentByteBuf.release();
//        JSONArray objects = JSONObject.parseArray(contentStr);
//        int id1 = (int) objects.get(1);
//        System.out.println(id1);
//        JSONObject jsonObject = JSON.parseObject(contentStr);
//        int id2 = (int) jsonObject.get("id");
//        System.out.println(id2);
        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set("custom-response-header", "Some value");
        returnSomething(response, ctx);
    }

    public void returnSomething(FullHttpResponse response, ChannelHandlerContext ctx) {
        String hello = "<h1> hello world </h1>";
        response.content().writeBytes(hello.getBytes());
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        QPSCalculator.getInstance().pass();
        System.out.println(QPSCalculator.getInstance().getAvgQps());
    }
}
